package com.common.groovy.action;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.common.dao.LowCodeDao;
import com.common.groovy.helper.GroovyHelper;
import com.common.groovy.model.ActionModel;
import com.common.groovy.model.DataModel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Date: 2025/6/30 13:36
 */
@Component("SimpleQueryOne")
public class SimpleQueryOneAction implements IAction<JSONObject, Object> {

    @Autowired
    private GroovyHelper groovyHelper;

    @Autowired
    private LowCodeDao lowCodeDao;

    @Override
    public Object execute(ActionModel actionDetail, DataModel data, JSONObject params) {
        Object result = Strings.EMPTY;
        String beforeShell = actionDetail.getBefore();
        String sql = actionDetail.getDetail().getSaveScript();
        String afterShell = actionDetail.getAfter();
        if (StringUtils.hasText(beforeShell)) {
            groovyHelper.execute(beforeShell, params);
        }
        if (StringUtils.hasText(sql)) {
            result = executeSql(sql, params);
        }
        if (StringUtils.hasText(afterShell)) {
            JSONObject afterParams = JSONUtil.createObj();
            afterParams.set("request", params);
            afterParams.set("response", result);
            groovyHelper.execute(afterShell, afterParams);
        }
        return result;
    }

    @Override
    public Object processSql(String sql) {
        List<Map<String, Object>> list = lowCodeDao.simpleQueryExecute(sql);
        if (CollectionUtils.isEmpty(list)) {
            return JSONUtil.createObj();
        }
        return JSONUtil.parseObj(list.get(0));
    }
}
